<template>
  <el-form
    :model="formData"
    ref="formRef"
    @submit.prevent
    :rules="formRules"
    label-width="110px"
    :disabled="mode === 'view'"
  >
    <el-row>
      <el-col>
        <el-form-item label="专家类型" prop="isInOut">
          <el-radio-group
            v-model="formData.isInOut"
            @change="handleChange"
            :disabled="mode !== 'add'"
          >
            <el-radio label="0">外部用户</el-radio>
            <el-radio label="1">内部用户</el-radio>
          </el-radio-group>
        </el-form-item></el-col
      >
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="姓名" prop="name">
          <el-input
            placeholder="请输入"
            v-model="formData.name"
            class="width-custom"
            v-if="formData.isInOut === '0'"
            :disabled="mode !== 'add'"
            clearable
          ></el-input>
          <el-select
            v-else
            v-model="formData.name"
            style="width: 100%"
            filterable
            remote
            placeholder="请输入姓名搜索"
            :remote-method="getTableLeaderData"
            value-key="id"
            clearable
            @change="handleSeleted"
            :disabled="mode !== 'add'"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item"
            ></el-option>
          </el-select> </el-form-item
      ></el-col>
      <el-col :span="12" v-if="formData.isInOut === '1'">
        <el-form-item label="账号名" prop="userName">
          <el-input
            v-model="formData.userName"
            class="width-custom"
            disabled
            clearable
            placeholder="选择姓名后自动带出"
          ></el-input> </el-form-item
      ></el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="邮箱" prop="email">
          <el-input
            type="email"
            v-model="formData.email"
            class="width-custom"
            clearable
            :disabled="formData.isInOut === '1'"
            :placeholder="
              formData.isInOut === '0' ? '请输入' : '选择姓名后自动带出'
            "
          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="手机" prop="phoneNum">
          <el-input
            :disabled="formData.isInOut === '1'"
            oninput="value=value.replace(/[^\d]/g,'')"
            v-model.number="formData.phoneNum"
            class="width-custom"
            clearable
            :placeholder="
              formData.isInOut === '0' ? '请输入' : '选择姓名后自动带出'
            "
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="工作单位" prop="companyName">
          <el-select
            :disabled="mode !== 'add' || formData.isInOut !== '0'"
            v-model="formData.companyName"
            style="width: 100%"
            filterable
            remote
            :placeholder="
              formData.isInOut === '0' ? '请输入' : '选择姓名后自动带出'
            "
            clearable
            :remote-method="searchCommanyData"
            value-key="id"
          >
            <el-option
              id="default-option"
              v-for="item in deptList"
              :key="item.id"
              :label="item.companyName"
              :value="item"
            ></el-option>
          </el-select> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="职务" prop="position">
          <el-input
            type="text"
            :disabled="mode === 'view'"
            v-model="formData.position"
            class="width-custom"
            placeholder="请输入"
            clearable
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="所学专业" prop="studyMajor">
          <el-input
            type="text"
            :disabled="mode === 'view'"
            v-model="formData.studyMajor"
            class="width-custom"
            placeholder="请输入"
            clearable
          ></el-input> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="职称" prop="ext5">
          <el-input
            type="text"
            :disabled="mode === 'view'"
            v-model="formData.ext5"
            class="width-custom"
            placeholder="请输入"
            clearable
          ></el-input> </el-form-item
      ></el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="现从事专业" prop="workMajor">
          <el-input
            type="text"
            :disabled="mode === 'view'"
            v-model="formData.workMajor"
            class="width-custom"
            placeholder="请输入"
            clearable
          ></el-input> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="专家组别" prop="ext1">
          <el-select
            style="width: 100%"
            value-key="key"
            multiple
            :disabled="mode === 'view'"
            v-model="formData.ext1"
            clearable
          >
            <el-option
              v-for="item in ext1s"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="其他资质" prop="otherQualifications">
          <el-input
            type="text"
            :disabled="mode === 'view'"
            v-model="formData.otherQualifications"
            class="width-custom"
            placeholder="请输入"
            clearable
          ></el-input> </el-form-item
      ></el-col>
    </el-row>

    <el-row>
      <el-col>
        <el-form-item label="专家简介" prop="remark">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            :disabled="mode === 'view'"
            v-model="formData.remark"
            clearable
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <el-row justify="end">
    <el-button @click="handleSubmit(false)">取 消</el-button>
    <el-button type="primary" :loading="btnloading" @click="handleSubmit(true)"
      >确 定</el-button
    >
  </el-row>
</template>

<script lang="ts">
import { cloneDeep } from "lodash-es";
import {
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRef,
  toRefs
} from "vue";
import { postDictList } from "/@/api/common";
import { postExpertStaffAdd, postExpertStaffUpdate } from "/@/api/expert";
import { postSysCompanyList } from "/@/api/organization";
import { getUsersForScience } from "/@/api/user";
import NotifMessage from "/@/utils/message/notification";
import { validatorEmail, validatorPhone } from "/@/utils/validator";
let principalCompanyArr = ref([]);

export default defineComponent({
  emits: ["emitSubmit"],
  props: {
    mode: {
      type: String,
      require: true,
      default: "add"
    },
    companyInfo: {
      type: Object,
      default: () => {}
    }
  },
  setup(props, { emit }) {
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const currentInfo = toRef(props, "companyInfo");
    const ext1s = ref([
      { key: "风味", label: "风味" },
      { key: "可持续发展", label: "可持续发展" },
      { key: "智能与数字化", label: "智能与数字化" },
      { key: "食品包装", label: "食品包装" },
      { key: "酿造技术及原料", label: "酿造技术及原料" },
      { key: "菌种酵母", label: "菌种酵母" },
      { key: "酒文化", label: "酒文化" },
      { key: "物流技术", label: "物流技术" },
      { key: "经济", label: "经济" }
    ]);
    let state = reactive({
      formData: {
        ext1: null,
        isInOut: "0",
        userId: "",
        name: null,
        userName: "",
        email: "",
        phoneNum: "",
        companyName: null,
        remark: "",
        studyMajor: "", //所学专业
        workMajor: "", //现从事专业
        position: "", //职务
        ext5: "", //职称
        otherQualifications: "" //其他资质
        // expAttachment: []
      },
      btnloading: false // 按钮加载
    });

    let userList = ref([]);

    let deptList = ref([]);
    onMounted(() => {
      initPrincipalCompanyList();
    });

    const initPrincipalCompanyList = async () => {
      try {
        const params = {
          dicType: "rd_principal_cmpy"
        };
        const { code, data } = await postDictList(params);
        if (code === 200) {
          principalCompanyArr.value = data;
        }
      } catch (err) {
        console.log(err);
      }
    };

    const initCommanyData = () => {
      getDeptData();
    };

    const searchCommanyData = (query = "") => {
      // if (!query) {
      //   deptList.value = [];
      //   return;
      // }
      getDeptData(query);
    };

    async function getDeptData(query = "") {
      try {
        const params = {
          pageNum: 1,
          pageSize: 0,
          companyNameLike: query
        };
        const { code, data } = await postSysCompanyList(params);
        if (code === 200) {
          deptList.value = data.list.map(item => {
            return { id: item.id, companyName: item.companyName };
          });
        }
      } catch (err) {
        console.log(err);
      }
    }

    const validateName = (rule: any, value: any, callback: any) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        if (value !== "") {
          const reg = /[a-zA-Z0-9_-]$/;
          if (!reg.test(value)) {
            callback(new Error("请输入字母，数字，下划线，减号"));
          }
        }
        callback();
      }
    };

    const formRules = ref({
      isInOut: [{ required: true, message: "请选择类型", trigger: "blur" }],
      email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        { required: true, validator: validatorEmail, trigger: "blur" }
      ],
      name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      userName: [
        {
          required: true,
          validator: validateName,
          trigger: "change"
        }
      ],
      phoneNum: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        { required: true, validator: validatorPhone, trigger: "blur" }
      ],

      companyName: [
        { required: true, message: "请输入公司名称", trigger: "blur" }
      ],
      studyMajor: [
        { required: true, message: "请输入所学专业", trigger: "blur" }
      ],
      ext1: [{ required: true, message: "请选择专家组别", trigger: "blur" }],
      workMajor: [
        { required: true, message: "请输入现从事专业", trigger: "blur" }
      ],
      position: [{ required: true, message: "请输入职务", trigger: "blur" }],
      ext5: [{ required: true, message: "请输入职称", trigger: "blur" }]
    });

    if (props.mode === "edit" || props.mode === "view") {
      const copyCurrentInfo = cloneDeep(currentInfo.value);
      state.formData.userId = copyCurrentInfo?.userId ?? "";
      state.formData.isInOut = copyCurrentInfo?.isInOut ?? "";
      state.formData.userName = copyCurrentInfo?.userName ?? "";
      state.formData.email = copyCurrentInfo?.email ?? "";
      state.formData.phoneNum = copyCurrentInfo?.phoneNum ?? "";
      state.formData.companyName = copyCurrentInfo?.companyName ?? "";
      state.formData.remark = copyCurrentInfo?.remark ?? "";
      state.formData.studyMajor = copyCurrentInfo?.studyMajor ?? "";
      state.formData.workMajor = copyCurrentInfo?.workMajor ?? "";
      state.formData.position = copyCurrentInfo?.position ?? "";
      state.formData.ext5 = copyCurrentInfo?.ext5 ?? "";
      state.formData.ext1 =
        copyCurrentInfo.ext1 && copyCurrentInfo.ext1.split(",");
      state.formData.otherQualifications =
        copyCurrentInfo?.otherQualifications ?? "";
      // state.formData.expAttachment = copyCurrentInfo?.otherQualifications ?? "";
      if (copyCurrentInfo.isInOut === "1") {
        state.formData.name = {
          id: copyCurrentInfo.userId,
          name: copyCurrentInfo.name,
          userName: copyCurrentInfo.userName,
          email: copyCurrentInfo.email,
          phoneNum: copyCurrentInfo.phoneNum
        };
        userList.value = [state.formData.name];
      } else {
        state.formData.name = copyCurrentInfo.name;
      }
    }

    const handleChange = val => {
      console.log(val);
      state.formData.userId = "";
      state.formData.name = null;
      state.formData.userName = "";
      state.formData.email = "";
      state.formData.phoneNum = "";
      state.formData.companyName = "";
      state.formData.remark = "";
      state.formData.studyMajor = "";
      state.formData.workMajor = "";
      state.formData.position = "";
      state.formData.ext5 = "";
      state.formData.ext1 = "";
      state.formData.otherQualifications = "";
      // state.formData.expAttachment = [];
      nextTick(() => {
        formRef.value.clearValidate();
      });
    };

    const handleSeleted = val => {
      if (val) {
        state.formData.userId = val.id;
        state.formData.userName = val.userName;
        state.formData.email = val.email;
        state.formData.phoneNum = val.phoneNum;
        state.formData.companyName = {
          id: val.companyId,
          companyName: val.companyName
        };
        if (deptList.value.findIndex(el => el.id === val.companyId) === -1) {
          deptList.value.push({
            id: val.companyId,
            companyName: val.companyName
          });
        }
      } else {
        state.formData.userId = "";
        state.formData.userName = "";
        state.formData.email = "";
        state.formData.phoneNum = "";
        userList.value = [];
        state.formData.companyName = null;
      }
    };

    async function getTableLeaderData(query = "") {
      if (!query) {
        userList.value = [];
        return;
      }
      try {
        const params = {
          pageNum: 1,
          pageSize: 200,
          name: query
        };
        const { code, data } = await getUsersForScience(params);
        if (code === 200) {
          userList.value = data.list.map(item => {
            return {
              id: item.id,
              name: item.name,
              userName: item.userName,
              email: item.email,
              phoneNum: item.phoneNum,
              companyId: item.deptCode,
              companyName: item.deptName
            };
          });
        }
      } catch (err) {
        console.log(err);
      }
    }

    // 确认提交或者取消
    const handleSubmit = async (isSubmit): Promise<void> => {
      if (isSubmit) {
        const isValid = await new Promise(resolve =>
          formRef.value.validate(resolve)
        );
        if (!isValid) return;
        const copeFormdata = cloneDeep(state.formData);
        copeFormdata.companyName =
          state.formData.companyName.companyName ||
          props.companyInfo.companyName;
        copeFormdata.companyId =
          state.formData.companyName.id || props.companyInfo.companyId;
        copeFormdata.ext1 = copeFormdata.ext1.join(",");
        if (state.formData.isInOut === "1") {
          copeFormdata.name = state.formData.name.name;
        }
        state.btnloading = true;
        if (props.mode === "edit") {
          copeFormdata.id = props.companyInfo.id;
          try {
            const { code, message } = await postExpertStaffUpdate(copeFormdata);
            requestSuccess(code, message, isSubmit);
          } catch {
            state.btnloading = false;
          }
        } else {
          // copeFormdata.phoneNum = copeFormdata.userName;
          // 外部专家的手机号保存为用户名
          if (state.formData.isInOut !== "1") {
            copeFormdata.userName = copeFormdata.phoneNum;
          }
          // copeFormdata.email = copeFormdata.phoneNum + "@admin.com";

          const { code, message } = await postExpertStaffAdd(copeFormdata);
          requestSuccess(code, message, isSubmit);
        }
      } else {
        emit("emitSubmit", isSubmit);
      }
      state.btnloading = false;
    };

    // 统一处理请求结果方法
    const requestSuccess = (
      code: number,
      message: string,
      isSubmit: boolean
    ) => {
      if (code === 200) {
        NotifMessage.success(message);
        emit("emitSubmit", isSubmit);
      } else {
        NotifMessage.success(message);
      }
    };

    return {
      ...toRefs(state),
      ext1s,
      userList,
      formRef,
      formRules,
      handleSubmit,
      handleChange,
      getTableLeaderData,
      handleSeleted,
      initCommanyData,
      searchCommanyData,
      principalCompanyArr,
      deptList
    };
  }
});
</script>
